﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace CRM.Database.Model
{
    public partial class TrainingsRequests : ISetChangedUser, IGetKeyValue
    {
        #region Implementation of ISetChangedUser

        /// <summary>
        /// Установка пользователя, который сделал изменение
        /// </summary>
        /// <param name="userLogin">Логин пользователя</param>
        public void SetChangedUser(string userLogin)
        {
            if (string.IsNullOrEmpty(userLogin))
                throw new Exception("Логин пользователя не должен быть пустым");
            IdUser = userLogin;
        }

        #endregion

        #region Implementation of IGetKeyValue

        /// <summary>
        /// Получение ключего значения элемента
        /// </summary>
        /// <returns>Ключевое значение</returns>
        public int GetKeyValue()
        {
            return IdTrainingsRequest;
        }

        #endregion

        /// <summary>
        /// заполнение нулевых значение пустыми строками
        /// </summary>
        public void Fill()
        {
            if (ContactName == null)
                ContactName = "";
            if (ContactPhone == null)
                ContactPhone = "";
            if (ContactEmail == null)
                ContactEmail = "";
            if (Comments == null)
                Comments = "";
            if (Company == null)
                Company = "";
            if (Reason == null)
                Reason = "";
        }

        #region Extended properties

        /// <summary>
        /// список участников заявки
        /// </summary>
        public List<TrainingsParticipants> Participants
        {
            get
            {
                var result = new List<TrainingsParticipants>();
                if (TrainingsParticipants != null)
                    result = TrainingsParticipants.ToList();
                return result;
            }
        }

        /// <summary>
        /// Название типа курса
        /// </summary>
        public string RequestType
        {
            get
            {
                if (IdTrainingsSchedule != null)
                    if (TrainingsSchedules != null)
                        if (TrainingsSchedules.TrainingsCourses != null)
                            if (TrainingsSchedules.TrainingCoursesTypes != null)
                                return TrainingsSchedules.TrainingCoursesTypes.LocalizedName;
                return "Выездной";
            }
        }

        /// <summary>
        /// Название компании для отображения
        /// </summary>
        public string CompanyExt
        {
            get
            {
                if (IdLegalEntity != null)
                {
                    var legalEntityCol = new LegalEntitiesCollection();
                    var entity = (LegalEntities) legalEntityCol.GetItemById((int) IdLegalEntity);
                    if (entity != null)
                        return entity.Name;
                }
                return "";
            }
        }

        /// <summary>
        /// Регион профайн
        /// </summary>
        public string profineRegion
        {
            get
            {
                if (IdLegalEntity != null)
                {
                    var legalEntityCol = new LegalEntitiesCollection();
                    var entity = (LegalEntities) legalEntityCol.GetItemById((int) IdLegalEntity);
                    if (entity != null)
                        return entity.ProfineRegionNameLocalized;
                }
                return "";
            }
        }
        
        /// <summary>
        /// Имя контактного лица для отображения
        /// </summary>
        public string ContactNameExt
        {
            get
            {
                if (IdContact != null)
                {
                    var contactsCol = new ContactsCollection();
                    var contact = (Contacts) contactsCol.GetItemById((int) IdContact);
                    if (contact != null)
                        return contact.Name;
                }
                return "";
            }
        }

        /// <summary>
        /// Название Города. Из площадки или напрямую.
        /// </summary>
        public string CityName
        {
            get
            {
                return TrainingsSchedules != null ? TrainingsSchedules.CityName : "";
            }
        }

        /// <summary>
        /// Отображение номера телефона
        /// </summary>
        public string ContactPhoneExt
        {
            get
            {
                if (IdContact != null)
                {
                    var contactsCol = new ContactsCollection();
                    var contact = (Contacts) contactsCol.GetItemById((int) IdContact);
                    //var contact = DB.GetContactById((int)IdContact);
                    if (contact != null)
                        return contact.Phone;
                }
                return "";
            }
        }

        /// <summary>
        /// Отображение почтового ящика
        /// </summary>
        public string ContactEmailExt
        {
            get
            {
                if (IdContact != null)
                {
                    var contactsCol = new ContactsCollection();
                    var contact = (Contacts) contactsCol.GetItemById((int) IdContact);
                    //var contact = DB.GetContactById((int)IdContact);
                    if (contact != null)
                        return contact.Email;
                }
                return "";
            }
        }

        /// <summary>
        /// имя курса для отображения
        /// </summary>
        public string CourseNameExt
        {
            get
            {
                if (TrainingsSchedules != null)
                    if (TrainingsSchedules.TrainingsCourses != null)
                        if (TrainingsSchedules.TrainingsCourses.Name != null)
                            return TrainingsSchedules.TrainingsCourses.Name;
                var coursesCol = new TrainingsCoursesCollection();
                var course = (TrainingsCourses) coursesCol.GetItemById(IdTrainingsCourse);
                //var course = DB.GetTrainingsCoursebyId(IdTrainingsCourse);
                if (course != null)
                    if (course.Name != null)
                        return course.Name;
                return "";
            }
        }

        /// <summary>
        /// Дата курса для отображения
        /// </summary>
        public string CourseDateExt
        {
            get
            {
                if (TrainingsSchedules != null)
                    return TrainingsSchedules.PlannedDate.ToShortDateString();
                return "";
            }
        }

        /// <summary>
        /// имя тренера для отображения
        /// </summary>
        public string TrainerNameExt
        {
            get
            {
                if (TrainingsSchedules != null)
                    if (TrainingsSchedules.TrainingsTrainers != null)
                        if (TrainingsSchedules.TrainingsTrainers.Name != null)
                            return TrainingsSchedules.TrainingsTrainers.Name;
                return "";
            }
        }

        /// <summary>
        /// Название центра обучения для отображения
        /// </summary>
        public string TraningCenterExt
        {
            get
            {
                if (TrainingsSchedules != null)
                    if (TrainingsSchedules.TrainingsTrainers != null)
                        if (TrainingsSchedules.TrainingsTrainers.TrainingsCenters != null)
                            if (TrainingsSchedules.TrainingsTrainers.TrainingsCenters.NameRu != null)
                                return TrainingsSchedules.TrainingsTrainers.TrainingsCenters.NameRu;
                return "";
            }
        }

        /// <summary>
        /// коэффициент явки
        /// </summary>
        public string VisitCoefficientExt
        {
            get
            {
                if (TrainingsSchedules != null)
                    return TrainingsSchedules.ParticipantsCountApproved.ToString() + "/" +
                           TrainingsSchedules.ParticipantsCountActual.ToString();
                return "";
            }
        }

        /// <summary>
        /// продолжительность курса
        /// </summary>
        public double DurationExt
        {
            get
            {
                if (TrainingsSchedules != null)
                    if (TrainingsSchedules.TrainingsCourses != null)
                        return TrainingsSchedules.TrainingsCourses.Duration;
                var coursesCol = new TrainingsCoursesCollection();
                var course = (TrainingsCourses) coursesCol.GetItemById(IdTrainingsCourse);
                return course != null ? course.Duration : 0;
            }
        }

        /// <summary>
        /// Продолжительность курса в виде текста
        /// </summary>
        public string DurationTxt
        {
            get
            {
                if (TrainingsSchedules != null)
                    if (TrainingsSchedules.TrainingsCourses != null)
                        return TrainingsSchedules.TrainingsCourses.Duration.ToString("F1");
                var coursesCol = new TrainingsCoursesCollection();
                var course = (TrainingsCourses) coursesCol.GetItemById(IdTrainingsCourse);
                //var course = DB.GetTrainingsCoursebyId(this.IdTrainingsCourse);
                return course != null ? course.Duration.ToString("F1") : " ";
            }
        }

        /// <summary>
        /// Стоимость курса для отображения
        /// </summary>
        public string CourseCostExt
        {
            get
            {
                if (TrainingsSchedules != null)
                    return TrainingsSchedules.CourseCost.ToString() + " руб.";
                return "";
            }
        }

        /// <summary>
        /// Статус курса для отображения
        /// </summary>
        public string StatusExt
        {
            get
            {
                if (TrainingRequestsStatuses != null)
                    return TrainingRequestsStatuses.NameRu;
                return "";
            }
        }

        /// <summary>
        /// Строка с участниками. Каждый на новой строке.
        /// </summary>
        public string ParticipantsList
        {
            get
            {
                string result = "";
                foreach (TrainingsParticipants participant in TrainingsParticipants)
                {
                    if (result.Length == 0)
                        result = result + participant.ParticipantName;
                    else
                        result = result + Environment.NewLine + participant.ParticipantName;
                }
                return result;
            }
        }

        /// <summary>
        /// Список участников, которым отказано в обучении
        /// </summary>
        public string ParticipantsRefusedList
        {
            get
            {
                string result = "";
                foreach (TrainingsParticipants participant in TrainingsParticipants)
                {
                    if (result.Length == 0)
                    {
                        if (participant.IdTrainingsParticipantsStatus == 5)
                            result = result + participant.ParticipantName;
                    }
                    else
                    {
                        if (participant.IdTrainingsParticipantsStatus == 5)
                            result = result + Environment.NewLine + participant.ParticipantName;
                    }
                }
                return result;
            }
        }

        /// <summary>
        /// Возвращает ссылку на карточку клиента для определенного менеджера
        /// </summary>
        /// <returns></returns>
        public string LinkForManagersRequests
        {
            get
            {
                if (IdCustomer == null) return "";
                if (IdCustomer > 0) return "http://ruw8kap01/CRM/Customers/Details/" + IdCustomer.ToString();
                return "";
            }
        }

        /// <summary>
        /// Заявка на плановый курс?
        /// </summary>
        public bool IsPlanned
        {
            get
            {
                if (TrainingsSchedules != null)
                    if (TrainingsSchedules.TrainingCoursesTypes != null)
                        if (TrainingsSchedules.TrainingCoursesTypes.IdTrainingCoursesType == 1)
                            return true;
                return false;
            }
        }

        /// <summary>
        /// Заявка на выездной курс?
        /// </summary>
        public bool IsRemote
        {
            get
            {
                if (TrainingsSchedules != null)
                    if (TrainingsSchedules.TrainingCoursesTypes != null)
                        if (TrainingsSchedules.TrainingCoursesTypes.IdTrainingCoursesType == 2)
                            return true;
                return false;
            }
        }

        /// <summary>
        /// Заявка на выбинар?
        /// </summary>
        public bool IsWebinar
        {
            get
            {
                if (TrainingsSchedules != null)
                    if (TrainingsSchedules.TrainingCoursesTypes != null)
                        if (TrainingsSchedules.TrainingCoursesTypes.IdTrainingCoursesType == 3)
                            return true;
                return false;
            }
        }

        /// <summary>
        /// Email менеждера (если есть)
        /// </summary>
        public string ManagerEmail
        {
            get
            {
                var customersCol = new CustomersCollection();
                var usersCol = new UsersCollection();
                if (IdCustomer != null)
                    if (IdCustomer > 0)
                    {
                        var customer = (Customers) customersCol.GetItemById(IdCustomer);
                        if (customer != null)
                        {
                            if (customer.IdManager != null)
                                if (customer.IdManager > 0)
                                {
                                    Users manager = usersCol.GetUserbyId((int) customer.IdManager);
                                    if (manager != null)
                                    {
                                        if (manager.UserEmail != null)
                                            return manager.UserEmail;
                                    }
                                }
                        }
                    }
                return "";
            }
        }

        /// <summary>
        /// Название рубрики
        /// </summary>
        public string RubricName
        {
            get
            {
                if (TrainingsSchedules != null)
                    if (TrainingsSchedules.TrainingsCourses != null)
                        return TrainingsSchedules.TrainingsCourses.RubricName;
                var coursesCol = new TrainingsCoursesCollection();
                var course = (TrainingsCourses)coursesCol.GetItemById(IdTrainingsCourse);
                if (course != null)
                        return course.RubricName;
                return "";
            }
        }

        /// <summary>
        /// Заявленное кол-во участников по курсу
        /// </summary>
        public double ParticipantsCountRequested
        {
            get
            {
                if(this.TrainingsSchedules!=null)
                {
                    return this.TrainingsSchedules.ParticipantsCountRequested;
                }
                return 0;
            }
        }

        /// <summary>
        /// Фактическое кол-во участников
        /// </summary>
        public double ParticipantsCountActual
        {
            get
            {
                if (this.TrainingsSchedules != null)
                {
                    return this.TrainingsSchedules.ParticipantsCountActual;
                }
                return 0;
            }
        }

        /// <summary>
        /// Стоимость курса
        /// </summary>
        public double CourseCost
        {
            get
            {
                return TrainingsSchedules != null ? TrainingsSchedules.CourseCost : 0;
            }
        }

        public string AuditoriumLocalizedName
        {
            get
            {
                if(this.IdTrainingsAuditorium > 0)
                {
                    var auditoriumCol = new TrainingsAuditoriumsCollection();
                    var auditorium = (TrainingsAuditoriums) auditoriumCol.GetItemById((int) IdTrainingsAuditorium);
                    if (auditorium != null)
                        return auditorium.LocalizedName;
                }
                return "";
            }
        }

        //название клиента
        public string CustomerName
        {
            get
            {
                if(this.IdLegalEntity!= null)
                {
                    var leCol = new LegalEntitiesCollection();
                    var le = (LegalEntities)leCol.GetItemById((int)this.IdLegalEntity);
                    if (le != null)
                        return le.CustomerName;
                }
                return "";
            }
        }

        #endregion
    }
}